package cn.yr.system.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import cn.yr.common.core.domain.dto.SysUserDto;
import cn.yr.common.core.domain.entity.SysUser;
import cn.yr.common.core.manager.AuthCacheManager;
import cn.yr.common.core.utils.jwt.JwtUtil;
import cn.yr.common.exception.ret.Ret;
import cn.yr.system.service.ILoginService;
import cn.yr.system.service.ISysUserService;
import me.zhyd.oauth.model.AuthUser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Lang 1102076808@qq.com
 * @description 微信登录授权
 * @date 2020-09-18 13:46
 */
@RestController
@RequestMapping("/wechatLogin")
public class LoginWechatController{

	@Value("${oauth.wechat.appID}")
	private String appId;
	@Value("${oauth.wechat.appSecret}")
	private String secret;

	@Resource
	private AuthCacheManager authCacheManager;

	@Resource
	private ISysUserService sysUserService;

	@Resource
	private ILoginService loginService;

	@PostMapping("/wechatLogin")
	public Ret wechatLogin(@RequestBody AuthUser authUser) {
		SysUserDto sysUserDtoTest = sysUserService.coverSysUser(authUser);
		SysUser user = sysUserDtoTest.getSysUser();
		/** 缓存用户信息与权限*/
		SysUserDto sysUserDto = loginService.initUser(user);
		authCacheManager.putUser(user.getUserId().toString(), sysUserDto);
		/** 返回token*/
		String token = JwtUtil.generateToken(user.getUserId().toString());
		Map<Object, Object> map = MapUtil.builder().put("userInfo", user).put("token", token).map();
		return Ret.success(map);
	}

	/**
	 * @description
	 * @author Lang
	 * @date 2020/9/18 13:47
	 */

	@GetMapping("/getWechatOpenId")
	public Ret getWechatOpenId(String code) {
		HashMap<String, Object> map = new HashMap<>(4);
		map.put("appid", appId);
		map.put("secret", secret);
		map.put("js_code", code);
		map.put("grant_type", "authorization_code");
		String res = HttpUtil.get(" https://api.weixin.qq.com/sns/jscode2session", map);
		String openid = JSONUtil.parseObj(res).getStr("openid");
		if (StrUtil.isNotEmpty(openid)) {
			return Ret.success(MapUtil.builder("openid",openid).map());
		} else {
			return Ret.error("未能获取到openid");
		}

	}
}
